import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pplive/common/utils.dart';
import 'package:pplive/models/extensions/moment_extensions.dart';
import 'package:pplive/models/moment_model.dart';

import '../../common/api_service.dart';

class SquarePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SquareState();
}

class _SquareState extends State<SquarePage>
    with SingleTickerProviderStateMixin {
  late ThemeData theme;
  late TabController _tabController;
  List<String> tabTitles = [
    "动态",
    "关注",
  ];
  ValueNotifier<int> selectedIndex = ValueNotifier(0);
  final ScrollController _scrollController = ScrollController();
  List<Moment> moments = [];
  int? _lastId;
  bool _isLoading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(_onScroll);
    selectedIndex = ValueNotifier(0);
    _tabController =
        TabController(vsync: this, initialIndex: 0, length: tabTitles.length);
    _tabController.addListener(() {
      reloadData();
    });
    onRefresh();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      fetchData(_lastId);
    }
  }

  void onTabSelected(int index) {
    // 处理页面切换逻辑
    print("Selected tab: $index");
  }

  void reloadData() {
    setState(() {});
  }

  Future<void> onRefresh() async {
    fetchData();
  }

  void fetchData([int? lastId]) {
    print("_isLoading: ${_isLoading} $lastId");
    if (_isLoading) {
      return;
    }
    _isLoading = true;
    var params = {"pageSize": 20, "follow": false};
    if (lastId != null) {
      params["lastId"] = lastId;
    }
    ApiService.postWithCallback<MomentModel>("/square/moment/listMoment",
        params: params, callback: (response) {
      if (response.code == ApiCodeSucc) {
        if (lastId == null) {
          moments = [];
        }
        var list = response.data?.moments ?? [];
        _lastId = list.last.momentId;
        moments.addAll(list);
        print("ret $lastId size: ${moments.length}");
        _isLoading = false;
        reloadData();
      } else {}
    });
  }

  @override
  Widget build(BuildContext context) {
    theme = Theme.of(context);
    return Scaffold(
      backgroundColor: theme.colorScheme.onSurface,
      appBar: AppBar(
          scrolledUnderElevation: 0,
          toolbarHeight: 0,
          title: Text("Home"),
          bottom: PreferredSize(
              preferredSize: Size.fromHeight(48),
              child: Container(
                  padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                  child: Row(
                    children: [
                      Expanded(
                        child: TabBar(
                            tabAlignment: TabAlignment.start,
                            isScrollable: true,
                            controller: _tabController,
                            tabs: tabTitles
                                .indexedMap(
                                    (index, titile) => Tab(text: titile))
                                .toList()),
                      ),
                      Container(
                        // width: 116,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            IconButton(
                              icon: const Icon(
                                Icons.save_as_sharp,
                                size: 22,
                              ),
                              onPressed: () {},
                            ),
                          ],
                        ),
                      )
                    ],
                  )))),
      body: SafeArea(
        child: Container(
            color: Colors.black,
            child: Padding(
                padding: EdgeInsets.fromLTRB(13, 0, 13, 0),
                child: moments.createView(onRefresh, _scrollController))),
      ),
    );
  }
}
